import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 角色
    roles: [],
    // 权限
    permissions: [],
  }),
  
  getters: {
    // 用户名
    username: (state) => state.userInfo?.username || '',
    // 是否已登录
    isLogin: (state) => !!state.userInfo,
    // 用户头像
    avatar: (state) => state.userInfo?.avatar || '',
    // 用户ID
    userId: (state) => state.userInfo?.userId || '',
    // 用户昵称
    nickname: (state) => state.userInfo?.nickname || '',
  },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      if (userInfo?.roles) {
        this.roles = userInfo.roles
      }
      if (userInfo?.permissions) {
        this.permissions = userInfo.permissions
      }
    },
    
    // 重置用户状态
    resetUserState() {
      this.userInfo = null
      this.roles = []
      this.permissions = []
    },
    
    // 退出登录
    logout() {
      // 清除用户信息
      this.resetUserState()
      // 清除localStorage中的token
      localStorage.removeItem('authenticationToken')
      localStorage.removeItem('refurbishToken')
    },
    
    // 判断是否有某个权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },
    
    // 判断是否有某个角色
    hasRole(role) {
      return this.roles.includes(role)
    }
  },
  
  // 持久化配置
  persist: {
    key: 'user-info',
    storage: localStorage,
    paths: ['userInfo', 'roles', 'permissions']
  }
}) 